//
//  LCWComposeViewController.swift
//  MyWB
//
//  Created by 李成万 on 16/7/3.
//  Copyright © 2016年 李成万. All rights reserved.
//

import UIKit

class LCWComposeViewController: UIViewController {

    let SideMargin : CGFloat = 5
    let TopMArgin = 100
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
    }
    
    func setupNav(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", style: UIBarButtonItemStyle.Plain, target: self, action: "OK")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    func setupUI(){
        setupNav()
//        view.backgroundColor = randomColor()
        view.addSubview(composeTextView)
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
        }
        
        toolBar.toolBarClosure = {[weak self] (type)->() in
            switch type{
            case .TuPian:
                self?.toolBarAddImage()
            case .AiTe:
                print("艾特")
            case .JingHao:
                print("井号")
            case .BiaoQing:
                self?.chooseKeyBoard()
            case .JiaHao:
                print("加号")
            }
        }
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionShow:", name: EmotionShow, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteBTnClick", name: deleteTextView, object: nil)
        composeTextView.addSubview(updatePicView)
        updatePicView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view).offset(SideMargin)
            make.trailing.equalTo(view).offset(-SideMargin)
            make.top.equalTo(composeTextView).offset(TopMArgin)
            make.height.equalTo(SCREENW - 2 * SideMargin)
        }
        
        updatePicView.updatePicCollectionViewClosure = {[weak self] ()->() in
            self?.toolBarAddImage()
            
        }
        
        
        
    }

    /**
     删除字符的通知方法
     */
    @objc private func deleteBTnClick(){
        composeTextView.deleteBackward()
    }
    @objc private func emotionShow(noti:NSNotification){
        
        guard let emotion = noti.object as? LCWEmotions else{
            return
        }
        
        if emotion.isEmoji {
            //            let selectRange = self.selectedRange
            //            self.text.insert(((emotion.code ?? "") as NSString).emoji(), atIndex: selectRange.location)
            composeTextView.insertText(((emotion.code ?? "") as NSString).emoji())
        }else{
            /*
            用富文本显示图片
            创建一个富文本,用富文本附件的形式初始化
            因为富文本附件可以显示图片
            然后创建富文本附件
            创建富文本附件需要注意设置他的 bounds
            bounds 中的宽高需要根据文本文字来确定,文本文字的字体有一个 lineHeight 属性可以拿到高度
            给富文本附件设置图片(拼接字符串地址然后用 bundle 创建图片)
            这时候可以看见直接给attributedText是不对的
            应该获取已有的内容然后进行拼接
            获取光标位置,然后在原来的内容中插入新加入的富文本
            但是继续输入表情,后面的表情大小发生了变化,所以我们应该对 oldAttr进行设置大小
            如果在中间输入表情的话,光标会跳到最后,所以我们应该手动改变光标的位置
            但是一开始就输入表情的话,占位文字和确定按钮不会改变,所以我们需要手动发通知调代理方法
            */
            
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)//bug 赋值不对
            
            let att = LCWEmotionAttr()
            let lineHeight = composeTextView.font!.lineHeight
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            let path = emotion.path ?? ""
            let png = emotion.png ?? ""
            let name = path + png
            
            att.image = UIImage(named:name , inBundle: LCWEmotionTools.sharedTools.emotionBundle, compatibleWithTraitCollection: nil)
            
            let attr = NSAttributedString(attachment: att)
            
            att.emotion = emotion
            let selectRange = composeTextView.selectedRange
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            oldAttr.addAttributes([NSFontAttributeName : composeTextView.font!], range: NSRange(location: 0, length: oldAttr.length))
            composeTextView.attributedText = oldAttr
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)//bug119 120互换
             NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
        }
    }
    /**
     监听键盘改变的方法
     
     - parameter noti: noti description
     */
    func keyboardFrameWillChange(noti:NSNotification){
//        print(noti)
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    func OK(){
        
        let attrText = composeTextView.attributedText
        
        var resultText = ""
        
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            if let attr = dict["NSAttachment"] as? LCWEmotionAttr {
                resultText += (attr.emotion?.chs ?? "")
            }else{
                let name = (attrText.string as NSString).substringWithRange(range)
                resultText += name
            }
        }
        
        
        if updatePicView.imageArr.count > 0{
            uploadTextWithPicWB(resultText, imageArray: updatePicView.imageArr)
        }else{
        updateTextWB(resultText)
        }
    }
    func cancel(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 底部 toolBar 的方法们
    /**
    添加图片的方法
    */
    func toolBarAddImage(){
        let picPick = UIImagePickerController()
        
        picPick.delegate = self
        presentViewController(picPick, animated: true, completion: nil)
    }
    /**
     切换键盘的 方法
     */
    func chooseKeyBoard(){
        
        if composeTextView.inputView == nil{
            composeTextView.inputView = emotionKeyboard
            toolBar.isKeyBoard = false
        }else{
            composeTextView.inputView = nil
            toolBar.isKeyBoard = true
        }
        //shuaxin!
        composeTextView.reloadInputViews()
        composeTextView.becomeFirstResponder()
        
    }
    // MARK: - 懒加载的控件们

    /// 导航栏标题
    private lazy var titleLabel : UILabel = {
        let lab = UILabel(messageColor: UIColor.grayColor(), textFont:15)
        let name = LCWUserAccountTools.sharedTool.userAccount?.screen_name ?? ""
        let str = "发微博\n\(name)"
        let attr = NSMutableAttributedString(string:str)
        let range = (str as NSString).rangeOfString(name)
        attr.addAttributes([NSForegroundColorAttributeName : ThemeColor,NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range)
        
        lab.textAlignment = .Center

        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.sizeToFit()
        return lab
    }()

    /// 发微博界面的文字输入
    private lazy var composeTextView : LCWComposeTextView =  {
        let textView = LCWComposeTextView()
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.placeHolder = "请输入微博内容"
        textView.font = UIFont.systemFontOfSize(20)
//        textView.textColor = UIColor.redColor()
        return textView
    }()
    
    private lazy var toolBar : LCWToolBar = LCWToolBar()
    private lazy var updatePicView : LCWUpdatePicCollectionView = LCWUpdatePicCollectionView()
    private lazy var emotionKeyboard : LCWEmotionKeyboard = {
        let view = LCWEmotionKeyboard()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        return view
    }()
    
    
    // MARK: - 销毁通知

    /**
     移除通知   
     */
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK: -  textView 的代理方法
extension LCWComposeViewController : UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}

// MARK: - 发微博的网络请求
extension LCWComposeViewController{
    // MARK: - 发送文字微博的方法
    func updateTextWB(content:String){
        LCWNetworkingTools.sharedTools.update(content, success: { (response) -> () in
            print("发微博成功")
            }) { (error) -> () in
                print("发微博失败")
        }
    }
    
    func uploadTextWithPicWB(content:String,imageArray:[UIImage]){
        LCWNetworkingTools.sharedTools.upload(content, imageArr: imageArray, success: { (response) -> () in
            print("发微博成功")
            }) { (error) -> () in
                 print("发微博失败\n\(error)")
        }
    }
}

// MARK: - 选择照片的代理
extension LCWComposeViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        composeTextView.backgroundColor = UIColor(patternImage:image)
//        let str =  "/Users/lichengwan/Desktop/Snip20160526_1.png"
//        let dataO = UIImagePNGRepresentation(image)
//        dataO?.writeToFile(str, atomically: true)
        //方式一
//        let data = UIImagePNGRepresentation(makeImageSmallerWithWidth(400, image: image))
//        data?.writeToFile(str, atomically: true)
        //方式2
//        let data = UIImageJPEGRepresentation(image, 0.2)
//        data?.writeToFile(str, atomically: true)
        
       updatePicView.addImage(makeImageSmallerWithWidth(400, image: image))
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    func makeImageSmallerWithWidth(width:CGFloat,image:UIImage)->UIImage{
        
        if image.size.width < width{
            return image
        }
        
        //获取压缩后的图片的高度
        let height = image.size.height * width / image.size.width
        
        //获取区域
        
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        //开启图形上下文
        UIGraphicsBeginImageContext(rect.size)
        //将图片渲染到上下文中
        image.drawInRect(rect)
        //获取上下文结果
        
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图形上下文
        UIGraphicsEndImageContext()
        
        return result
        
    }
}